package com.cg;

import java.util.concurrent.*;

/**
 * CompleteFuture api allOf和anyOf区分
 * anyOf：返回最优先执行完成的completeFuture
 * allOf：所有任务执行完毕后,返回null
 *
 */
public class CompleteFutureTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        CompletableFuture<String> cf7 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println(Thread.currentThread() + " cf7 do something....");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("cf7 任务完成");
            return "cf7 任务完成";
        });

        CompletableFuture<String> cf8 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println(Thread.currentThread() + " cf8 do something....");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("cf8 任务完成");
            return "cf8 任务完成";
        });

        CompletableFuture<String> cf9 = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println(Thread.currentThread() + " cf9 do something....");
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("cf9 任务完成");
            return "cf9 任务完成";
        });

        CompletableFuture<Void> cfAll = CompletableFuture.allOf(cf7, cf8, cf9);
        System.out.println("cfAll结果->" + cfAll.get());

//        CompletableFuture<Object> cfAny = CompletableFuture.anyOf(cf7, cf8, cf9);
//        System.out.println("cfAny结果->" + cfAny.get());
        long endTime = System.currentTimeMillis() - startTime;
        System.out.println("总耗时："+ endTime);
    }
}
